package com.taritari.journal.services;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taritari.journal.entity.dto.CommentDto;
import com.taritari.journal.entity.dto.UserLikeDto;
import com.taritari.journal.entity.po.Comment;
import com.taritari.journal.entity.po.JournalUser;
import com.taritari.journal.entity.po.TestPo;
import com.taritari.journal.entity.vo.CommentReplay;
import com.taritari.journal.entity.vo.CommentVo;
import com.taritari.journal.entity.vo.ERNIEBotVo;
import com.taritari.journal.mapper.CommentMapper;
import com.taritari.journal.mapper.TestMapper;
import com.taritari.journal.mapper.TreeHoleMapper;
import com.taritari.journal.services.impl.CommentServiceImpl;
import com.taritari.journal.services.impl.TestServiceImpl;
import com.taritari.journal.utils.BaiDuApiUtil;
import com.taritari.journal.utils.DateUtil;
import io.netty.util.internal.StringUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author taritari
 * @date 2024-01-24 15:11
 * @description 评论表
 */
@Service
public class CommentService extends ServiceImpl<CommentMapper, Comment> implements CommentServiceImpl {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private DateUtil dateUtil;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private BaiDuApiUtil baiDuApiUtil;
    @Autowired
    private TreeHoleMapper treeHoleMapper;

    /**
     * 通过树洞id查询所有评论
     * */
    @Override
    public List<Comment> selectAllCommentByTreeHoldId(int treeHoldId, int orderBy) {
        LambdaQueryWrapper<Comment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Comment::getTreeholeId,treeHoldId);
        lambdaQueryWrapper.eq(Comment::getIsDelete,0);
        if (orderBy == 0){
            lambdaQueryWrapper.orderByDesc(Comment::getCreatedTime);
        }
        List<Comment> comments = commentMapper.selectList(lambdaQueryWrapper);
        return comments;
    }
    /**
     * 添加评论
     * 如果有replayId就是回复评论
     * */
    @Override
    public int insertComment(CommentDto commentDto) {
        int res = commentMapper.insertComment(commentDto.getTreeHoldId(), commentDto.getContent(), commentDto.getAuthorId(), commentDto.getReplyId());
        return res;
    }
    /**
     * 通过树洞id查询评论总条数
     * */
    @Override
    public int getCount(int treeHoldId) {
        int count = commentMapper.queryCountByTreeHoldId(treeHoldId);
        return count;
    }

    /**
     * 获取评论接口
     * */
    public List<CommentVo> getComment(int treeHoldId,int orderBy){
        List<Comment> comments = selectAllCommentByTreeHoldId(treeHoldId, orderBy);
        // 筛选出replyToCommentId为空和replyToCommentId不为空的评论
        List<Comment> replayComment = comments.stream().filter(comment -> comment.getReplyToCommentId() != null).collect(Collectors.toList());
        List<Comment>  mainComment = comments.stream().filter(comment -> comment.getReplyToCommentId() == null).toList();
        System.out.println(replayComment);
        List<CommentVo> commentList = new ArrayList<>();
        for(Comment item : mainComment){
            CommentVo commentVo = new CommentVo();
            // 通过id获取用户信息
            JournalUser journalUser = userService.queryUserInfoById(item.getAuthorId());
            // 用户名
            commentVo.setName(journalUser.getNickname());
            // 评论id
            commentVo.setId(item.getId());
            // 用户头像
            commentVo.setImgUrl(journalUser.getImgUrl());
            // 评论时间
            commentVo.setTime(dateUtil.dateFormat(item.getCreatedTime()));
            // 内容
            commentVo.setContent(item.getContent());
            // 作者id
            commentVo.setAuthor_id(journalUser.getId());
            // 喜欢
            commentVo.setLikes(item.getLikes());
            // 创建评论实例
            List<CommentReplay> replays = new ArrayList<>();
            List<Comment> replayList = replayComment
                    .stream()
                    .filter(comment -> Objects.equals(comment.getReplyToCommentId(), String.valueOf(item.getId())))
                    .toList();
            for (Comment replay : replayList){
                CommentReplay commentReplay = new CommentReplay();
                // 通过id获取用户信息
                JournalUser replayJournalUser = userService.queryUserInfoById(replay.getAuthorId());
                commentReplay.setName(replayJournalUser.getNickname());
                commentReplay.setContent(replay.getContent());
                commentReplay.setTime(dateUtil.dateFormat(replay.getCreatedTime()));
                commentReplay.setAuthor_id(replayJournalUser.getId());
                commentReplay.setId(commentReplay.getId());
                replays.add(commentReplay);
            }
            commentVo.setReplay(replays);
            commentList.add(commentVo);
        }
        return commentList;
    }
    /**
     * 查询用户是否喜欢评论
     * */
    public int userIsLikeComment(int userId,int commentId){
        int res = commentMapper.queryCommentIsLike(userId, commentId);
        return res;
    }
    /**
     * 用户点击喜欢
     * */
    public int userClickLike(int userId, int commentId) {
        int res = commentMapper.queryCommentIsLike(userId, commentId);
        if (res == 1){ //存在-再点一次就不喜欢
            commentMapper.commentLikesChanges(-1,commentId);
            int r = commentMapper.deleteCommentLike(userId, commentId);
            return r;
        }else { //不存在-点一次就喜欢
            commentMapper.commentLikesChanges(1,commentId);
            int r = commentMapper.insertCommentLike(userId,commentId);
            return r;
        }
    }
    /**
     * rabbitmq的生产者
     * @param
     * */
    public void commentLikeMq(UserLikeDto userLikeDto){
        String jsonString = JSON.toJSONString(userLikeDto);
        // 交换机名
        String exchangeName = "journal_comment";
        //路由名，由交换机绑定
        String routingKey = "like";
        rabbitTemplate.convertAndSend(exchangeName,routingKey,jsonString);
    }


    /**
     * 文心4.0评论日记
     * */
    public int botComment(String text,String number){
        //检查是否已经评论
        Integer  treeHoldId = treeHoleMapper.queryIdByJourNalNumber(number);
        int comment = commentMapper.isComment(treeHoldId, 1);
        if (comment>0){
            return 0;
        }
        // 然后从redis获取百度api的token
        String accessToken = stringRedisTemplate.opsForValue().get("qianFanaccessToken");

        // m没有就重新获取
        if (StringUtil.isNullOrEmpty(accessToken)){
            accessToken = baiDuApiUtil.getQianFanToken();
        }
        //准备数据
        List<Map<String,String >> dataList = new ArrayList<>();
        Map<String,String> userContent = new HashMap<>(8);
        Map<String,Object> dataMap = new HashMap<>(8);
        userContent.put("role","user");
        //设置具体prompt
        StringBuffer messages = new StringBuffer("你现在是一个对内容进行评论的评论家，我需要你对我传入的内容进行评论。我需要评论，不是总结，吧自己当成一个读着，字数100左右，评论内容正向。 只需回复我评论内容就行。下面是内容：");
        messages.append(text);
        userContent.put("content",messages.toString());
        dataList.add(userContent);
        dataMap.put("messages",dataList);
        String jsonString = JSONObject.toJSONString(dataMap);
        ERNIEBotVo ernieBotVo = baiDuApiUtil.wenXinWorkShop(accessToken, jsonString);
        String commentContent = ernieBotVo.getResult();
        //获取到评论内容~进行评论
        int res = commentMapper.insertComment(treeHoldId,commentContent, 1, null);
        return res;
    }
}
